package com.example.controller;

import com.example.entity.Goods;
import com.example.entity.GoodsCollectionDTO;
import com.example.entity.User;
import com.example.entity.UserCollection;
import com.example.service.CollectionService;
import com.example.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/collection")
public class CollectionController {

    @Autowired
    private CollectionService collectionService;
    @Autowired
    private GoodsService goodsService;

    // 显示收藏列表
    @GetMapping("/list")
    public String collectionList(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login"; // 未登录跳转到登录页
        }
        List<GoodsCollectionDTO> UserCollection = collectionService.getUserCollections(user.getUid());
        System.out.println(UserCollection);
        model.addAttribute("UserCollection", UserCollection);
        return "student/collections";
    }

    // 添加收藏
    @RequestMapping("/add")
    public ModelAndView addCollection(@RequestParam int gid, HttpSession session) {
        User user = (User) session.getAttribute("user");
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        ModelAndView mv = new ModelAndView();
        if (user != null) {
            collectionService.addCollection(user.getUid(), gid, time);

            int page = 1;
            int pageNum = 6;
            List<Goods> goods = this.goodsService.findGoodsByPage(page, pageNum);
            int totalPage = this.goodsService.totalPage(pageNum);

            mv.setViewName("student/home");
            mv.addObject("goods", goods);
            mv.addObject("currentPage", page);
            mv.addObject("totalPage", totalPage);
        }
        return mv;
    }
    @RequestMapping("/remove")
    public ModelAndView remove(@RequestParam int collectionid, HttpSession session){
        User user = (User) session.getAttribute("user");
        ModelAndView mv = new ModelAndView();
        collectionService.remove(collectionid);
        List<GoodsCollectionDTO> UserCollection = collectionService.getUserCollections(user.getUid());
        mv.setViewName("student/collections");
        mv.addObject("UserCollection", UserCollection);
        return mv;
    }
}